package com.tpod.taxi.view.componment;

import tpod.network.HTTPCachePolicy;
import tpod.network.HTTPRequest;
import tpod.network.HTTPRequestDelegate;
import tpod.network.http.reponse.HTTPBitmapResponse;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AutoLoadImageView extends ImageView {

	private Handler mHandler;
	private HTTPRequest mRequest;
	private RequestDelegate delegate;
	private String currentUrl;
	private Bitmap currentBitmap;
	private int errorResId;

	public AutoLoadImageView(Context context) {
		this(context, null);
	}

	public AutoLoadImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mHandler = new Handler();
		this.delegate = new RequestDelegate();
	}

	public void setErrorResource(int resId) {
		this.errorResId = resId;
	}

	public void setHandler(Handler mHandler) {
		this.mHandler = mHandler;
	}

	public synchronized void setImageUrl(String url, HTTPCachePolicy policy) {
		if (currentUrl == url && currentBitmap != null)
			return;
		cancelRequest();
		reload(url);
	}

	private void cancelRequest() {
		mRequest.cancel();
	}

	private void reload(String url) {
		mRequest = new HTTPRequest(url, this.delegate);
		mRequest.setCachePolicy(HTTPCachePolicy.LOCAL);
		mRequest.setResponse(new HTTPBitmapResponse());
		mRequest.send();
	}

	private class RequestDelegate extends HTTPRequestDelegate {

		@Override
		public void onRequestCancel(HTTPRequest arg0) {
			currentBitmap = null;
		}

		@Override
		public void onRequestError(HTTPRequest arg0, Throwable arg1) {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					AutoLoadImageView.this.setImageResource(errorResId);
				}
			});
		}

		@Override
		public void onRequestReponse(HTTPRequest arg0) {
			final HTTPBitmapResponse reponse = (HTTPBitmapResponse) arg0
					.getResponse();
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					setImageBitmap(reponse.bitmap);
					currentBitmap = reponse.bitmap;
				}
			});
		}

		@Override
		public void onRequestStart(HTTPRequest arg0) {

		}

	}
}
